package cn.edu.nit.sys.service.impl;

import cn.edu.nit.common.exception.SysBaseError;
import cn.edu.nit.sys.entity.Teacher;
import cn.edu.nit.sys.mapper.TeacherMapper;
import cn.edu.nit.sys.service.TeacherService;
import cn.edu.nit.sys.utils.R;
import cn.edu.nit.sys.vo.TeacherVO;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;

/**
 * @Author xiaobai
 * @Date 2022/10/1 14:17
 * @Version 1.0.0
 */
@Service
public class TeacherServiceImpl extends ServiceImpl<TeacherMapper, Teacher> implements TeacherService {

    @Override
    public R getList(Page<Teacher> page, TeacherVO teacherVO) {
        Page<Teacher> list = baseMapper.getList(page, teacherVO);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", list.getRecords());
        jsonObject.put("total", list.getTotal());
        return R.ok(jsonObject);
    }

    @Override
    @Transactional
    public R add(Teacher teacher) {
        String pos = baseMapper.findPos(teacher.getPosition());
        if (StringUtils.isEmpty(pos) && StringUtils.isNotEmpty(teacher.getPosition())) {
            int i = baseMapper.addPos(teacher.getPosition());
            if(i == 0) {
                throw new SysBaseError("自定义职位插入失败");
            }
        }
        String lastOneId = "" + baseMapper.findLastOneId();
        String substring = "";
        if(StringUtils.isNotEmpty(lastOneId)) {
            substring = lastOneId.substring(0, 4);
        }
        Calendar instance = Calendar.getInstance();
        String YEAR = "" + instance.get(Calendar.YEAR);
        if(!YEAR.equals(substring)) {
            String id = YEAR + 200001;
            teacher.setId(Long.parseLong(id));
        }
        int insert = baseMapper.insert(teacher);
        return insert > 0 ? R.ok("添加成功") : R.error("添加失败");
    }


}
